#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// gcc 06_pthread_lock.c -lpthread

//定义一把互斥锁
pthread_mutex_t mutex;

void *print_string(void *arg)
{
    char *str = (char *)arg;
    int i=0;
    // printf("[%s] start ... \n", str);
    //上锁
    pthread_mutex_lock(&mutex);

    while(str[i] != 0) {
        printf("%c", str[i]);
        fflush(stdout);
        sleep(1);
        i++;
    }
    //解锁
    pthread_mutex_unlock(&mutex);
}

int main(int argc, char const *argv[])
{
    //初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    pthread_t tid1;
    pthread_t tid2;
    pthread_t tid3;

    pthread_create(&tid1, NULL, print_string, "hello");
    pthread_create(&tid2, NULL, print_string, "world");
    pthread_create(&tid3, NULL, print_string, "string");

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    
    //销毁锁
    pthread_mutex_destroy(&mutex);
    return 0;
}